Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

307
Vistas
Django REST Framework - "Must be Device instance" error when calling PUT from javascript

I'm getting an error when trying to update an object instance using PUT using the rest framework: ValueError: Cannot assign "{'id': UUID('954...8b4')}": "DeviceConfig.device" must be a "Device" instance.

view defn:

class DeviceConfigViewSet(viewsets.ModelViewSet):
    #todo: secure
    authentication_classes = []
    queryset = DeviceConfig.objects.all().order_by('device')
    def get_queryset(self):
        device = self.get_renderer_context()["request"].query_params.get('device')
        if device:
            return DeviceConfig.objects.filter(device=Device(device=device))[0:]
        else:
            return self.queryset
    serializer_class = DeviceConfigSerializer

DeviceConfig model:

class DeviceConfig(models.Model):
    device = models.OneToOneField(Device,primary_key=True,on_delete=models.CASCADE)
    bpm = models.DecimalField(max_digits=22, decimal_places=3, blank=True, null=True, default=0.5)
    duty = models.DecimalField(max_digits=22, decimal_places=4, blank=True, null=True, default=0.022)
    ledState = models.IntegerField(
        default=255,
        validators=[MaxValueValidator(255), MinValueValidator(0)]
     )
    pressureMax = models.IntegerField( blank=True, null=True, default=70, validators=[MaxValueValidator(255), MinValueValidator(10)])

JS func FE side:

   function formSubmit(){
        var myForm = document.getElementById("config-form");
        var formObj = new FormData(myForm);
        var object = {};
        formObj.forEach(function(value, key){
            object[key] = value;
        });
        object["device"] = DEVICE_UUID;
        const putMethod = {
            method: 'PUT',
            headers: {
            'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
            },
            body: JSON.stringify(object) 
        }
        fetch("http://localhost:81/configs/"+DEVICE_UUID, putMethod);
    }

I've tried not sending the device ID from the front end but it gives me a 400 then the ol' goog search didn't turn up much for me this time, but I'm not quite sure how to send a Device instance from the client side besides by it's pk which is what I've tried

EDIT - DeviceConfigSerializer

class DeviceConfigSerializer(serializers.HyperlinkedModelSerializer):
    device = serializers.UUIDField(source='device.id')
    class Meta:
        model = DeviceConfig
        fields = ('device','bpm', 'duty','ledState','pressureMax')
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I worked it out. @JPG helped point in the right direction, it was the serializer - i was needlessly referencing device, which was screwing things up. I've removed it from the serializer and JS and all works well now. Thanks for pointing me in the right direction @JPG

Given the reference to the device ID was already in the url I was calling, there's no need to pass it in again. I'm still not quite sure how to interpret the error (insight appreciated) but my thoughts are it was attempting to assign a plain UUID where it needed a Device instance, which was not being handled in my serializer code as I thought it was.

Cheers

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda